package git.soulbgm.service.impl;

import git.soulbgm.service.LoginService;
import org.mockito.internal.util.io.IOUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Properties;

/**
 * 登录服务实现
 *
 * @author SoulBGM
 * @date 2022/03/22 17:20
 */
@Service
@ConfigurationProperties(prefix = "sys.auth")
public class LoginServiceImpl implements LoginService {

    private String file;

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        Properties props = System.getProperties();
        if (!file.contains("/") && !file.contains("\\")) {
            file = props.getProperty("user.dir") + "/" + file;
        }
        this.file = file;
    }

    @Override
    public boolean login(String username, String password) {
        try {
            Collection<String> lines = IOUtil.readLines(new FileInputStream(file));
            for (String l : lines) {
                String[] split = l.split(":");
                if (split.length != 2) {
                    continue;
                }
                if (username.equals(split[0]) && password.equals(split[1])) {
                    return true;
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("sys.auth.file配置的文件路径有误");
        }
        return false;
    }

    @Override
    public boolean changePassword(String username, String password) {
        return false;
    }
}
